package com.example.demo.controller;

import com.example.demo.pojo.RoleEntity;
import com.example.demo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    // 分页列表
    @GetMapping("/page")
    public ResponseEntity<?> getRolePage(@RequestParam int current, @RequestParam int size) {
        System.out.println("/role/page");
       // 计算分页起始位置
        int offset = (current - 1) * size;

        // 获取当前页数据
        List<RoleEntity> roles = roleService.getRolePage();

        // 获取总记录数
        int total = roleService.getRoleCount();

        // 构建响应数据
        Map<String, Object> response = new HashMap<>();
        response.put("result", Map.of(
            "records", roles,   // 当前页的记录
            "current", current, // 当前页码
            "size", size,       // 每页大小
            "total", total      // 总记录数
        ));
        System.out.println(roles.size());
        return ResponseEntity.ok(response);
    }

    // 获取所有角色
    @GetMapping("/list")
    public ResponseEntity<List<RoleEntity>> getAllRoles() {
        return ResponseEntity.ok(roleService.getAllRoles());
    }

    // 添加角色
    @PostMapping("/save")
    public ResponseEntity<RoleEntity> saveRole(@RequestBody RoleEntity role) {
        return ResponseEntity.ok(roleService.addRole(role));
    }

    // 更新角色
    @PostMapping("/update")
    public ResponseEntity<RoleEntity> updateRole(@RequestBody RoleEntity role) {

        return ResponseEntity.ok(roleService.updateRole(role));
    }
    @PostMapping("/updateRoleMenu")
    public ResponseEntity<String> updateRoleMnue(@RequestBody RoleEntity role) {
        System.out.println("updateRoleMenu");
        System.out.println(role.getType());
        roleService.updateRoleMnue(role);
        return ResponseEntity.ok("更新成功");
    }

    // 删除角色
    @GetMapping("/del")
    public ResponseEntity<?> deleteRole(@RequestParam String name) {
        roleService.deleteRole(name);
        return ResponseEntity.ok("删除成功");
    }

    // 获取单个角色详情
    @GetMapping("/{id}")
    public ResponseEntity<RoleEntity> getRoleById(@PathVariable Long id) {
        return ResponseEntity.ok(roleService.getRoleById(id));
    }
}
